package com.bangdream.michelia.presenter;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.bangdream.michelia.contract.AdContract;
import com.bangdream.michelia.entity.AdBean;
import com.bangdream.michelia.entity.DownLoadInfo;
import com.bangdream.michelia.model.IAdModelImpl;
import com.bangdream.michelia.presenter.base.IPresenterImpl;
import com.bangdream.michelia.tool.rejava.BaseObserverResponseBodyNormalHttp;
import com.bangdream.michelia.tool.rejava.BaseObserverStringNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.DownLoadManager;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.MyLog;
import com.bangdream.michelia.utils.SPUtils;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Mr.Wang on 2018/3/30.
 * 909732184@qq.com
 */

public class AdPresenter<V> extends IPresenterImpl<V> {
    private static final String TAG = "AdPresenter";
    private AdContract.IAdModel model;
    final AdBean adBean = new AdBean();
    public AdPresenter() {
        model = new IAdModelImpl();
        adBean.setNmTime(3);
        adBean.setPlayAd(true);
        //adBean.setStPictureUrl("http://img.zcool.cn/community/0142135541fe180000019ae9b8cf86.jpg@1280w_1l_2o_100sh.png");
        adBean.setStPictureUrl("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=187628756,1814270653&fm=27&gp=0.jpg");
        adBean.setStWebUrl("https://www.baidu.com/");
    }
    @Override
    public void startLoadData() {
        final AdContract.IAdView iView = getMyView();
        if (iView == null)
            return;
        model.getAdData("")
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(null,pd) {
                    @Override
                    public void onHandleSuccess(String t) {
                        getAdMessage();
                    }
                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        getAdMessage();
                    }
                });
    }

    private void getLocalPicture(AdContract.IAdView iAdView,String localUrl) {
        Bitmap bitmap = BitmapFactory.decodeFile(localUrl);
        iAdView.setAdTime(AdPresenter.this.adBean.getNmTime());
        iAdView.setAdData(AdPresenter.this.adBean);
        iAdView.setAdImg(bitmap);
    }

    public void getAdMessage() {
        model.getAdMessage()
                .compose(composeFunction)
                .subscribe(new BaseObserverStringNormalHttp(null,pd){
                    @Override
                    public void onHandleSuccess(String t) {
                        //此处应该获取到广告实例adBean 由于网络原因先固定死数据
                        getAdPicture(AdPresenter.this.adBean.getStPictureUrl(), "Advertisement.jpg");
                    }
                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        getAdPicture(AdPresenter.this.adBean.getStPictureUrl(), "Advertisement.jpg");
                    }
                });

    }

    public void getAdPicture(final String fileUrl, final String fileName) {
        //获取要展示的广告图片
        final AdContract.IAdView view = getMyView();
        if (view == null)
            return;
        if (SPUtils.get((Context) view, "adPictureUrl", "").equals(fileUrl)) {//判断是否存在缓存
            MyLog.d(TAG,"从本地获取图片");
            getLocalPicture(view,(String) SPUtils.get((Context) view,"adPictureAddress",""));
        } else {
            DownLoadAdFile(fileUrl,fileName);
        }
    }
    //下载广告图文件
    public void DownLoadAdFile(final String url,final String fileName){
        MyLog.d(TAG,"从网络中获取图片"+url);
        //获取要展示的广告图片
        final AdContract.IAdView view = getMyView();
        if (view == null)
            return;
        Observable apiserice  = RetroFactory.getInstance().downloadFile(url);
        apiserice.compose(composeFunction).subscribe(new BaseObserverResponseBodyNormalHttp(null,null) {
            @Override
            public void onHandleSuccess(final ResponseBody t) {
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                        String stLocalUrl = ((Context) view).getExternalFilesDir(null) + File.separator + fileName;
                        DownLoadInfo downLoadInfo = new DownLoadInfo();
                        downLoadInfo.setLocalUrl(stLocalUrl);
                        String path = DownLoadManager.writeResponseBodyToDisk((Context) view, t,downLoadInfo);
                        if (path != null && path.length() > 0) {
                            e.onNext(path);
                        } else {
                            e.onNext(null);
                        }
                        e.onComplete();
                    }
                })
                //将被观察者切换到子线程
                .subscribeOn(Schedulers.io())
                //将观察者切换到主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                        MyLog.d(TAG,"下载文件的本地地址为："+s);
                        //下载好广告图片后，保存好当前广告图片的地址，为判断是否已经下载好图片做准备
                        SPUtils.put((Context) view, "adPictureAddress", ((Context) view).getExternalFilesDir(null) + File.separator + fileName);
                        SPUtils.put((Context) view, "adPictureUrl", url);
                        view.setAdTime(AdPresenter.this.adBean.getNmTime());
                        view.setAdData(AdPresenter.this.adBean);
                        view.setAdImg(BitmapFactory.decodeFile(s));
                    }
                });
            }
        });
    }
    public AdContract.IAdView getMyView() {
        return (AdContract.IAdView) obtainView();
    }
}
